#include <stdio.h>
#include "ohos_init.h"
#include "cmsis_os2.h"
#include "iot_gpio.h"
#include "iot_gpio_ex.h"
#include "iot_fan_key.h"
#include "iot_fan_motor.h"

#define KEY_IO_GPIO_05  5


/* 初始化按键的GPIO */
void AgricultureKeyInit(void)
{
    // 初始化GPIO-5引脚
    int ret = IoTGpioInit(KEY_IO_GPIO_05);
	if(ret != KP_ERR_SUCCESS){ 
        printf("IoTGpioInit failed :%#x \r\n",ret); 
		return;
    }
	
    /* 设置复用为GPIO功能 */
	ret = IoTGpioSetFunc(KEY_IO_GPIO_05, IOT_GPIO_FUNC_GPIO_5_GPIO);
	if(ret != KP_ERR_SUCCESS){ 
        printf("IoTGpioSetFunc failed :%#x \r\n",ret);
		return;
    }

    ret = IoTGpioSetDir(KEY_IO_GPIO_05, IOT_GPIO_DIR_IN);
    if (ret != KP_ERR_SUCCESS) {
        printf("IoTGpioSetDir failed :%#x \r\n",ret); 
        return;
    }
	
    printf("----- AgricultureKeyGpioInit success! -----\r\n");
}

/* 按键处理任务，周期检测按键状态，如果按下则处理 */
void AgricultureKeyTask(void)
{
    AgricultureKeyInit();
	
    /* 变量初始化 */
    u32 ret = 0;
	IotGpioValue key_value = IOT_GPIO_VALUE1; //按钮的状态
	static int motor_level = 0; //风扇的档位，分为三档
	
    /* 循环检测按键状态并处理 */
    while (1) {
		ret = IoTGpioGetInputVal(KEY_IO_GPIO_05, &key_value);
		if (ret != KP_ERR_SUCCESS) {
	        printf("IoTGpioGetInputVal failed :%#x \r\n", ret); 
	        return;
	    }

        /* 当key_value为低电平时说明按下了按键，按1次按键增加一个档位 */
		if (IOT_GPIO_VALUE0 == key_value) {
			printf("key pressed :%#x \r\n", key_value);
			/* 防抖   */
			sleep(1);
			if (IOT_GPIO_VALUE0 == key_value) {
				motor_level++;
				if (motor_level >= 4) {
					motor_level = 0;
			    }
				printf("motor speed level :%d \r\n", motor_level);
		    }

			/* 按照key_value的值来控制风扇转速 */
			switch (motor_level) {
				case 0:
					/* 关闭风扇 */
			        AgricultureMotorCtrl(MOTOR_SPEED_LEVEL_0);
					break;
				case 1:
					/* 一档风扇 */
				    AgricultureMotorCtrl(MOTOR_SPEED_LEVEL_1);
					break;
				case 2:
					/* 二档风扇 */
					AgricultureMotorCtrl(MOTOR_SPEED_LEVEL_2);
					break;
				case 3:
					/* 三档风扇 */
					AgricultureMotorCtrl(MOTOR_SPEED_LEVEL_3);
					break;
				default:
					printf("invalid motor speed level! \r\n");
			}
	    }
    }

    return;
}
 
